var express = require('express');
var router = express.Router();
var multer = require('multer');
var upload = multer({dest:"public/images/upload/"}).single('file1');
//加密模块
var crypto = require('crypto');
var User = require('../models/user.js');
var Blog = require('../models/blog.js');
var Comment = require('../models/comment.js');
/* GET home page. */
module.exports = function(app){

	//首页显示
	app.get('/',function(req,res){
		//判断是否是第一页，并把请求页数转化成数字
		var page = req.query.p?parseInt(req.query.p):1;

		//获取page页的第十篇文章
		Blog.getTen(null,page,function(err,blogs,total){
			if(err){
				blogs = [];
			}
			res.render('index', { 
				title: '主页',
				user: req.session.user,
				blogs:blogs,
				page:page,
				isFirstPage:(page-1)==0,
				isLastPage:((page-1)*2+blogs.length)>=total,
				success: req.flash('success').toString(),
				error: req.flash('error').toString(),
			});
		});
/*		Blog.getAll(null,function(err,blogs){
			//console.log(JSON.stringify(blogs));
			if(err){
				blogs = [];
			}
			res.render('index', { 
				title: '主页',
				user: req.session.user,
				blogs:blogs,
				success: req.flash('success').toString(),
				error: req.flash('error').toString(),
			});
		});*/
	});
	//登录页面显示
	app.get('/login',checkLogout);
	app.get('/login',function(req,res){
		res.render('login', { 
			title: '登录' ,
			user: req.session.user,
			success: req.flash('success').toString(),
			error: req.flash('error').toString(),
		});
	});
	//登录验证
	app.post('/login',checkLogout);
	app.post('/login',function(req,res){
		var md5 = crypto.createHash('md5');
		var password = md5.update(req.body.password).digest('hex');
		User.get(req.body.name,function(err,user){
			if(err){
				req.flash('error','用户不存在');
				return res.redirect('/login');
			}
			//验证密码
			if(user.password!=password){
				req.flash('error','用户密码错误');
				return res.redirect('/login');
			}

			//验证通过后，密码写入session
			req.session.user = user;
			req.flash('success','登录成功');
			return res.redirect('/');//登录成功后跳转到主页
		});
	})
	//登出
	app.get('/logout',checkLogin);
	app.get('/logout',function(req,res){
		req.session.user = null;
		req.flash('success','登出成功');
		return res.redirect('/');//登出后返回到主页
	});
	//注册页面
	app.get('/reg',checkLogout);
	app.get('/reg',function(req,res){
		res.render('register', { 
			title: '注册',
			user: req.session.user,
			success: req.flash('success').toString(),
			error: req.flash('error').toString(),
		});
	});
	//提交注册信息
	app.post('/reg',checkLogout);
	app.post('/reg',function(req,res){
		var name = req.body.name;
		var password = req.body.password;
		var password2 = req.body.password2;
		console.log(name+password+password2)
		if(password != password2){
			req.flash('error','两次输入的密码不一致。');
			return res.redirect('/reg');//返回注册页面
		}

		//生成密码md5
		var md5 = crypto.createHash('md5');
		var password = md5.update(req.body.password).digest('hex');
		var newUser = new User({
			name: req.body.name,
			password: password,
			email: req.body.email
		});
		//检查用户是否存在
		User.get(newUser.name,function(err,user){
			
			if(err){
				req.flash('error',err);

				return res.redirect('/reg');
			}
			if(user){
				req.flash('error','用户已经存在');
				return res.redirect('/reg');
			}
			//如果不存在，则新增用户
			newUser.save(function(err,user){
				if(err){
					req.flash('error',err);
					console.log(err);
					return res.redirect('/reg');
				}
				//添加成功后把用户信息写入session，返回主页
				req.session.user = user;
				req.flash('success','用户注册成功');
				res.redirect('/');
			});

		});
	});

	//发表博客页面
	app.get('/post',checkLogin);
	app.get('/post',function(req,res){
		res.render('post',{
			title: '发表博客',
			user: req.session.user,
			success: req.flash('success').toString(),
			error: req.flash('error').toString(),
		})
	});
	//发表博客
	app.post('/post',checkLogin);
	app.post('/post',function(req,res){
		var currentUser = req.session.user;
		console.log(req.body.tag1);
		var tags = [req.body.tag1,req.body.tag2,req.body.tag3];
		var blog = new Blog({
			name: currentUser.name,
			title: req.body.title,
			blog: req.body.blog,
			tags: tags,
		});

		blog.save(function(err){
			if(err){
				console.log(err);
				req.flash('error','保存失败')
				return res.redirect('/post');
			}
			req.flash('success','保存成功');
			res.redirect('/');//发表成功，跳转到主页
		});

	});
	//上传图片的页面
	app.get('/upload',checkLogin);
	app.get('/upload',function(req,res){
		res.render('upload',{
			title:'上传图片',
			user: req.session.user,
			success: req.flash('success').toString(),
			error: req.flash('error').toString()
		});
	});
	
	//上传文件
	app.post('/upload',checkLogin);
	app.post('/upload',function(req,res){
		upload(req, res, function (err) {
		if (err) {
			console.log(err); 
			req.flash('error','文件上传失败');
			res.redirect('/upload');
			}
		})
		req.flash('success','文件上传成功');
		res.redirect('/upload');
	});

	app.get('/u/:name',function(req,res){

		var page = req.query.p?parseInt(req.query.p):1;
		//判断是否存在该用户
		User.get(req.params.name,function(err,user){
			if(!user){
				req.flash('error','用户不存在');
				return res.redirect('/');
			}
			//获取page页的第十篇文章
			Blog.getTen(user.name,page,function(err,blogs,total){
				if(err){
					blogs = [];
				}
				res.render('index', { 
					title: user.name,
					user: req.session.user,
					blogs:blogs,
					page:page,
					isFirstPage:(page-1)==0,
					isLastPage:((page-1)*10+blogs.length)==total,
					success: req.flash('success').toString(),
					error: req.flash('error').toString(),
				});
			});
/*			//获取该作者的说有文章
			Blog.getAll(user.name,function(err,blogs){
				if(err){
					req.flash('error','用户不存在');
					return res.redirect('/');
				}
				res.render('user',{
					title: user.name,
					blogs: blogs,
					user: req.session.user,
					success: req.flash('success').toString(),
					error: req.flash('error').toString()
				});
			});*/
		});
	});

	app.get('/u/:name/:day/:title',function(req,res){
		console.log("huoqu"+req.path);
		Blog.getOne({
			name: req.params.name,
			day: req.params.day,
			title: req.params.title
		},function(err,blog){
			if(err){
				req.flash('error',err);
				return res.redirect('/');
			}
			console.log(JSON.stringify(blog));
			res.render('article',{
				title: req.params.title,
				blog: blog,
				user: req.session.user,
				success: req.flash('success').toString(),
				error: req.flash('error').toString()
			});
		});
	});
	//保存留言信息
	app.post('/u/:name/:day/:title',function(req,res){
		var newComment = new Comment({
			name: req.params.name,
			day: req.params.day,
			title: req.params.title,
			comment: {
				name: req.body.name,
				email: req.body.email,
				website: req.body.website,
				content: req.body.content
			}

		});
		newComment.save(function(err){
			if(err){
				req.flash('error',err);
				return res.redirect('back');
			}
			req.flash('success','留言成功');
			res.redirect('back');
		});
	});
	// 获取编辑页面
	app.get('/edit/:name/:day/:title',checkLogin);
	app.get('/edit/:name/:day/:title',function(req,res){
		var currentUser = req.session.user;
		Blog.edit({
			name:req.session.user.name,
			day:req.params.day,
			title:req.params.title
		},function(err,blog){
			if(err){
				req.flash('error',err);
				return res.redirect('back');
			}
			res.render('edit',{
				title:'编辑',
				blog:blog,
				user:req.session.user,
				success:req.flash('success').toString(),
				error:req.flash('error').toString()
			})
		});
	});
	//保存修改信息
	app.post('/edit/:name/:day/:title',checkLogin);
	app.post('/edit/:name/:day/:title',function(req,res){
		var url = encodeURI('/u/'+req.params.name+'/'+req.params.day+'/'+req.params.title);
		Blog.update({
			name:req.session.user.name,
			day:req.params.day,
			title:req.params.title
		},req.body.blog,function(err){
			if(err){
				req.flash('error',err);
				return res.redirect('back');
			}

			req.flash('success','保存成功');
			res.redirect(url);
		});
	});
	//删除一篇文章
	app.get('/remove/:name/:day/:title',checkLogin);
	app.get('/remove/:name/:day/:title',function(req,res){
		Blog.remove({
			name:req.session.user.name,
			day:req.params.day,
			title:req.params.title
		},function(err){
			if(err){
				req.flash('error',err);
				return res.redirect('back');
			}
			req.flash('success','删除成功');
			res.redirect('/');
		})
	});
	//添加存档的路由规则
	app.get('/archive',function(req,res){
		Blog.getArchive(function(err,blogs){
			if(err){
				req.flash('error',err);
				res.redirect('/');
			}
			req.flash('success','获取存档成功');
			res.render('archive',{
				title:'存档',
				blogs:blogs,
				user:req.session.user,
				success:req.flash('success').toString(),
				error:req.flash('error').toString()
			});
		});
	});
	app.get('/tags',function(req,res){
		Blog.getTags(function(err,blogs){
			if(err){
				req.flash('error',err);
				return res.redirect('/');
			}
			res.render('articleTags',{
				title:'标签',
				blogs:blogs,
				user:req.session.user,
				success:req.flash('success').toString(),
				error:req.flash('error').toString()
			});
		});
	});
	app.get('/tags/:tag',function(req,res){
		Blog.getBlogByTag(req.params.tag,function(err,blogs){
			if(err){
				req.flash('error',err);
				return res.redirect('/');
			}
			console.log(blogs.length);
			res.render('tag',{
				title: 'TAG:'+req.params.tag,
				blogs:  blogs,
				user: req.session.user,
				success: req.flash('success').toString(),
				error: req.flash('error').toString()
			})
		});
	});
	// 查询博客
	app.get('/search',function(req,res){
		Blog.search(req.query.keyword,function(err,blogs){
			if(err){
				req.flash('error',err);
				return res.redirect('/');
			}
			res.render('search',{
				title:'SEARCH'+req.query.keyword,
				blogs:blogs,
				user:req.session.user,
				success:req.flash('success').toString(),
				error:req.flash('error').toString()
			});
		});
	});
	app.get('/reprint/:name/:day/:title',checkLogin);
	app.get('/reprint/:name/:day/:title',function(req,res){
		Blog.reprint({
			'name':req.params.name,
			'day':req.params.day,
			'title':req.params.title
		},{
			'name':req.session.user.name,
		},function(err,blog){
			if(err){
				req.flash('error',err);
				return res.redirect('back');
			}
			req.flash('success','转载成功');
			var url = encodeURI('/u/'+blog.name+'/'+blog.time.day+'/'+blog.title);
			res.redirect(url);
		});
	})

	// 404页面
	app.use(function(req, res, next) {
		console.log(req.path);
	  	var err = new Error('Not Found');
	 	err.status = 404;
	 	res.send('404');
	});
};



//检测用户登录状态
var checkLogin = function(req,res,next){
	if(!req.session.user){
		req.flash('error','未登录，请重新登录');
		return　res.redirect('/');
	}
	next();
}
var checkLogout = function(req,res,next){
	if(req.session.user){
		req.flash('error','已经登录');
		return　res.redirect('back');//返回之前的页面
	}
	next();
}